var chargeStartedApp = angular.module("chargeStarted", []);
chargeStartedApp.controller("chargeStartedController", function($scope, $rootScope, $window, scCodeService, Popup, $location,$q,pubFun) {
    //是否正在充电
    var openCharge = localStorage.getItem("openCharge");
    //获取token
    var token = localStorage.getItem("token");
    //获取用户卡号
    var userCard = localStorage.getItem("cardNo");
    //獲取用戶id
    var userId = localStorage.getItem("userId");
    var pushTimeout='';
    //獲取用戶id
    //webSocket
    var webSocket = new WebSocket("ws://" + window.location.host + "/appserver/static/websocket/" + userId);
    webSocket.onerror = function(event) {
        
    };
    webSocket.onopen = function(event) {
        
    };
    webSocket.onmessage = function(event) {
        
        var websocketdata=JSON.parse(event.data);
        var websocketdata_data=JSON.parse(websocketdata.data);
        $scope.loadingToastHide();
        //
        if(websocketdata.action == "1001"){   //预约成功推送
            chargeSn = websocketdata_data.reservationSn;
            //alert("websocket chargeSn:"+chargeSn);
            
            localStorage.setItem("reservationSn", reservationSn);
            window.location.href=mainConfig.hostUrl+"index.html?#/appointing/" + reservationSn;
        }else if(websocketdata.action == "1002"){   //开启充电成功推送
            if(websocketdata_data.actionType=="1" || websocketdata_data.actionType==1){
                chargeSn = websocketdata_data.chargeSn;
                //alert("websocket chargeSn:"+chargeSn);
                
                clearInterval(pushTimeout);
                localStorage.setItem("chargeSn", chargeSn);
                window.location.href = mainConfig.hostUrl + "index.html?#/charging/"+chargeSn;
            }
        }else if(websocketdata.action == "1003"){    //结束充电成功推送
            var orderNo = websocketdata_data.orderNo;
            localStorage.setItem("orderNo",orderNo);
            //alert("websocket orderNo:"+orderNo);
            
            $scope.openCharge = "false";
            localStorage.setItem("openCharge", $scope.openCharge);
            window.location.href=mainConfig.hostUrl+"index.html?#/orderPay/" + orderNo;        
        }
        
    };
    // alert(openCharge);
        //监听againScanController获取桩详情
        // $scope.$watch(function() {
        //     return $window.chargerDetail;
        // });
        // $scope.chargerDetail = $window.chargerDetail;
        $scope.chargerDetail = JSON.parse(localStorage.getItem("chargerDetail"));
        
        // localStorage.setItem("chargerDetail", JSON.stringify($scope.chargerDetail));
    //判断是否通过二维码进入开始充电页面
    if ($scope.chargerDetail == undefined||$scope.chargerDetail == null) {
        $location.path("/index_");
    } else {
         //alert("桩号"+JSON.stringify($scope.chargerDetail));
        //遍历plugNoList
        var plugNoList = $scope.chargerDetail.plugNoList;
        for (var i = 0; i < plugNoList.length; i++) {
            var plugNoList = plugNoList[i];
        }
        $scope.chargerDetail.chargeStatus = plugNoList.chargeStatus;
        //chargerId and plugNo
        localStorage.setItem("chargerId", $scope.chargerDetail.chargerId);
        localStorage.setItem("plugNo", plugNoList.portNo);
        //获取费率
        $scope.getRate = function() {
            var postData = {
                chargerId: $scope.chargerDetail.chargerId
            }
            // alert("桩号"+JSON.stringify($scope.chargerDetail));
            scCodeService.getRate(postData).then(function(data) {
                //费率处理
                for (var i = 0; i < data.data.length; i++) {
                    if (data.data[i].feeType == 3) {
                        $scope.serveRate = data.data[i].rate;
                        $scope.serveMode = data.data[i].chargeMode;
                        $scope.serveModeStr= data.data[i].chargeMode=="0"?"度":"次";
                    }
                }
                for (var i = 0; i < data.data.length; i++) {
                    if (data.data[i].feeType == 2) {
                        $scope.chargerRate = data.data[i].rate;
                    }
                }
                localStorage.setItem("rate", $scope.chargerRate);
            })

        }
        $scope.getRate();
        //开启充电
        //判断桩的详情
        //if (plugNoList.chargeStatus == 0) {
            
            $scope.startCharge = function() {
                var postData = {
                    chargerId: $scope.chargerDetail.chargerId,
                    userCard: userCard,
                    chargerPlugNo: plugNoList.portNo,
                    token: token,
                    source:mainConfig.source,
                    merchantCode:mainConfig.merchantCode
                };
                var isLogin = localStorage.getItem("isLogin");
                if (isLogin == "true") {
                    $q.all([pubFun.getPending(), pubFun.getOngoingOperation()]).then(function(data) {
                            if (globalFun.isEmptyObj(data[0]) == false) {
                                var notPayCardNo = data[0][0].orderNo;
                                $scope.weirdConfirmSet({
                                    title: "",
                                    content: "你有一个未支付的订单",
                                    buttonAux: '取消',
                                    buttonMain: '立即支付',
                                    icon: "pending",
                                    data: { type: "3", orderNo: notPayCardNo } //type: "1"，取消预约 "2"，结束充电 "3"，有未支付 "4"，有充电业务 "5"，有充预约务
                                });
                            } else if (globalFun.isEmptyObj(data[1].chargeList) == false) {
                                $scope.weirdConfirmSet({
                                    title: "",
                                    content: "您有一项充电任务正在进行中",
                                    buttonAux: '取消',
                                    buttonMain: '去看看',
                                    icon: "charge",
                                    data: { type: '4', msg: data[1].chargeList[0] } //type: "1"，取消预约 "2"，结束充电 "3"，有未支付 "4"，有充电业务 "5"，有充预约务
                                });
                            } else {
                                    //在不存在未支付、进行中业务的情况下，进行充电
                                    $scope.loadingToastSet("充电请求中...");
                                    //$scope.loadingToastHide();
                                    
                                    //alert(JSON.stringify(postData));
                                    scCodeService.openCharge(postData).then(function(data) {
                                        //alert(JSON.stringify(data));
                                        if (data.code == "200") {
                                            
                                            //获取开始时间
                                            var temp = new Date();
                                            var Y = temp.getFullYear() + '-';
                                            var M = (temp.getMonth()+1 < 10 ? '0'+(temp.getMonth()+1) : temp.getMonth()+1) + '-';
                                            var D = temp.getDate() + ' ';
                                            var h = temp.getHours();
                                            if(h<10){
                                                h = "0" + h;
                                            }
                                            var m = temp.getMinutes();
                                            if(m<10){
                                                m = "0" + m;
                                            }
                                            var s = temp.getSeconds();
                                            if(s<10){
                                                s = "0" + s;
                                            } 
                                            var result = Y+M+D+h+":"+m+":"+s;
                                            var SMS = Date.parse(temp);
                                            // var regex = /\//g;
                                            // var result = (temp.toLocaleDateString("zh-cn") + ' ' + temp.toLocaleTimeString("en-GB",{hour12: false})).replace(regex, '-');
                                            localStorage.setItem("SMS", SMS);
                                            
                                            localStorage.setItem("startTime", result);
                                            //判断充电开启状态
                                            $scope.openCharge = "true";
                                            localStorage.setItem("openCharge", $scope.openCharge);
                                            //开启充电推送超时处理
                                            var num = 0;
                                            pushTimeout = setInterval(function() {
                                                num++;
                                                if (num > mainConfig.overTimeSeconds) {
                                                    clearInterval(pushTimeout);
                                                    pubFun.getOngoingOperation().then(function (data) {
                                                        if (globalFun.isEmptyObj(data.chargeList) == false){ //如果存在正在充电的业务
                                                            angular.forEach($scope.chargeList, function(data, index, array) {
                                                                $scope.loadingToastHide();
                                                                if(array[index].chargerId==postData.chargerId && array[index].portNo==postData.chargerPlugNo){  //进行桩和枪口的匹配
                                                                    window.location.href=mainConfig.hostUrl+'index.html?#/charging/'+array[index].chargeSn;
                                                                }
                                                            });
                                                            
                                                        }
                                                    });
                                                }
                                            }, 1000);
                                        } else if(data.code=="300") {   //已被预约或正在充电
                                            $scope.loadingToastHide();
                                            
                                            Popup.notice('充电桩使用中', 3000);
                                        } else {
                                            $scope.loadingToastHide();
                                            
                                            Popup.notice("充电桩暂不可用", 3000);
                                        }
                                    })
                                
                            }
                        })
                    
                } else {
                    localStorage.setItem("state",3)
                    $rootScope.showLogin = true;
                }
                
            }
        /*} else if (plugNoList.chargeStatus == 2) {
            Popup.notice('充电桩使用中', 3000, function() {
                
            });
        } else {
            Popup.notice('充电桩不可用', 3000, function() {
                
            });
        }*/
    }
})
